<html lang="en-US">

<head>
    
<title>Go 泛型的 3 个核心设计，你学会了吗？ - 花落雨忧</title>

<meta property="og:title" content="Go 泛型的 3 个核心设计，你学会了吗？ - 花落雨忧">



    



    
    <meta property="description" content="大家好，我是煎鱼。
Go1.18 的泛型是闹得沸沸扬扬，虽然之前写过很多篇针对泛型的一些设计和思考。但因为泛型的提案之前一直还没定型，所以就没有写完整介绍。
如今已经基本成型，就由煎鱼带大家一起摸透 Go 泛型。本文内容主要涉及泛型的 3 大概念，非常值得大家深入了解。
如下：
[&amp;hellip;] 类型参数，这个名词。不熟悉的小伙伴咋一看就懵逼了。
泛型代码是使用抽象的数据类型编写的，我们将其称 &amp;hellip;">
    <meta property="og:description" content="大家好，我是煎鱼。
Go1.18 的泛型是闹得沸沸扬扬，虽然之前写过很多篇针对泛型的一些设计和思考。但因为泛型的提案之前一直还没定型，所以就没有写完整介绍。
如今已经基本成型，就由煎鱼带大家一起摸透 Go 泛型。本文内容主要涉及泛型的 3 大概念，非常值得大家深入了解。
如下：
[&amp;hellip;] 类型参数，这个名词。不熟悉的小伙伴咋一看就懵逼了。
泛型代码是使用抽象的数据类型编写的，我们将其称 &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/generics-design/">Go 泛型的 3 个核心设计，你学会了吗？</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2022/02/05</a>
                                            
                                            
                                            
                                            
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p>大家好，我是煎鱼。</p>
<p>Go1.18 的泛型是闹得沸沸扬扬，虽然之前写过很多篇针对泛型的一些设计和思考。但因为泛型的提案之前一直还没定型，所以就没有写完整介绍。</p>
<p>如今已经基本成型，就由煎鱼带大家一起摸透 Go 泛型。本文内容主要涉及泛型的 3 大概念，非常值得大家深入了解。</p>
<p>如下：</p>
<ul>
<li>类型参数。</li>
<li>类型约束。</li>
<li>类型推导。</li>
</ul>
<h2 id="类型参数">类型参数</h2>
<p>类型参数，这个名词。不熟悉的小伙伴咋一看就懵逼了。</p>
<p>泛型代码是使用抽象的数据类型编写的，我们将其称之为类型参数。当程序运行通用代码时，类型参数就会被类型参数所取代。也就是<strong>类型参数是泛型的抽象数据类型</strong>。</p>
<p>简单的泛型例子：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Print</span>(<span style="color:#a6e22e">s</span> []<span style="color:#a6e22e">T</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">v</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">s</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">v</span>)
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>代码有一个 <code>Print</code> 函数，它打印出一个片断的每个元素，其中片断的元素类型，这里称为 T，是未知的。</p>
<p>这里引出了一个要做泛型语法设计的点，那就是：T 的<strong>泛型类型参数，应该如何定义</strong>？</p>
<p>在现有的设计中，分为两个部分：</p>
<ul>
<li>类型参数列表：<strong>类型参数列表将会出现在常规参数的前面</strong>。为了区分类型参数列表和常规参数列表，类型参数列表<strong>使用方括号</strong>而不是小括号。</li>
<li>类型参数约束：如同常规参数有类型一样，类型参数也有元类型，被称为约束（后面会进一步介绍）。</li>
</ul>
<p>结合完整的例子如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#75715e">// Print 可以打印任何片断的元素。
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// Print 有一个类型参数 T，并有一个单一的（非类型）的 s，它是该类型参数的一个片断。
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Print</span>[<span style="color:#a6e22e">T</span> <span style="color:#a6e22e">any</span>](<span style="color:#a6e22e">s</span> []<span style="color:#a6e22e">T</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#75715e">// do something...
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>}
</span></span></code></pre></div><p>在上述代码中，我们声明了一个函数 <code>Print</code>，其有一个类型参数 T，类型约束为 <code>any</code>，表示为任意的类型，作用与 <code>interface{}</code> 一样。他的入参变量 <code>s</code> 是类型 T 的切片。</p>
<p>函数声明完了，在函数调用时，我们需要指定类型参数的类型。如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>	<span style="color:#a6e22e">Print</span>[<span style="color:#66d9ef">int</span>]([]<span style="color:#66d9ef">int</span>{<span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">2</span>, <span style="color:#ae81ff">3</span>})
</span></span></code></pre></div><p>在上述代码中，我们指定了传入的类型参数为 int，并传入了 <code>[]int{1, 2, 3}</code> 作为参数。</p>
<p>其他类型，例如 float64:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span>	<span style="color:#a6e22e">Print</span>[<span style="color:#66d9ef">float64</span>]([]<span style="color:#66d9ef">float64</span>{<span style="color:#ae81ff">0.1</span>, <span style="color:#ae81ff">0.2</span>, <span style="color:#ae81ff">0.3</span>})
</span></span></code></pre></div><p>也是类似的声明方式，照着套就好了。</p>
<h2 id="类型约束">类型约束</h2>
<p>说完类型参数，我们再说说 “约束”。在所有的类型参数中都要指定类型约束，才能叫做完整的泛型。</p>
<p>以下分为两个部分来具体展开讲解：</p>
<ul>
<li>定义函数约束。</li>
<li>定义运算符越苏</li>
</ul>
<h3 id="为什么要有类型约束">为什么要有类型约束</h3>
<p>为了<strong>确保调用方能够满足接受方的程序诉求</strong>，保证程序中所应用的函数、运算符等特性能够正常运行。</p>
<p>泛型的类型参数，类型约束，相辅相成。</p>
<h3 id="定义函数约束">定义函数约束</h3>
<h4 id="问题点">问题点</h4>
<p>我们看看 Go 官方所提供的例子：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Stringify</span>[<span style="color:#a6e22e">T</span> <span style="color:#a6e22e">any</span>](<span style="color:#a6e22e">s</span> []<span style="color:#a6e22e">T</span>) (<span style="color:#a6e22e">ret</span> []<span style="color:#66d9ef">string</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">v</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">s</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">ret</span> = append(<span style="color:#a6e22e">ret</span>, <span style="color:#a6e22e">v</span>.<span style="color:#a6e22e">String</span>()) <span style="color:#75715e">// INVALID
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>	}
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">ret</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>该方法的实现目的是：任何类型的切片都能转换成对应的字符串切片。但程序逻辑里有一个问题，那就是他的入参 T 是 <code>any</code> 类型，是任意类型都可以传入。</p>
<p>其内部又调用了 <code>String</code> 方法，自然也就会报错，因为只像是 int、float64 等类型，就可能没有实现该方法。</p>
<p>你说要定义有效的类型约束，那像是上面的例子，在泛型中如何实现呢？</p>
<p>要求传入方要有内置方法，就得定义一个 <code>interface</code> 来约束他。</p>
<h4 id="单个类型">单个类型</h4>
<p>例子如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Stringer</span> <span style="color:#66d9ef">interface</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">String</span>() <span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>在泛型方法中应用：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Stringify</span>[<span style="color:#a6e22e">T</span> <span style="color:#a6e22e">Stringer</span>](<span style="color:#a6e22e">s</span> []<span style="color:#a6e22e">T</span>) (<span style="color:#a6e22e">ret</span> []<span style="color:#66d9ef">string</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">v</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">s</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">ret</span> = append(<span style="color:#a6e22e">ret</span>, <span style="color:#a6e22e">v</span>.<span style="color:#a6e22e">String</span>())
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">ret</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>再将 <code>Stringer</code> 类型放到原有的 <code>any</code> 类型处，就可以实现程序所需的诉求了。</p>
<h4 id="多个类型">多个类型</h4>
<p>如果是多个类型约束。例子如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Stringer</span> <span style="color:#66d9ef">interface</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">String</span>() <span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Plusser</span> <span style="color:#66d9ef">interface</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">Plus</span>(<span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">ConcatTo</span>[<span style="color:#a6e22e">S</span> <span style="color:#a6e22e">Stringer</span>, <span style="color:#a6e22e">P</span> <span style="color:#a6e22e">Plusser</span>](<span style="color:#a6e22e">s</span> []<span style="color:#a6e22e">S</span>, <span style="color:#a6e22e">p</span> []<span style="color:#a6e22e">P</span>) []<span style="color:#66d9ef">string</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">r</span> <span style="color:#f92672">:=</span> make([]<span style="color:#66d9ef">string</span>, len(<span style="color:#a6e22e">s</span>))
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">i</span>, <span style="color:#a6e22e">v</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">s</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">r</span>[<span style="color:#a6e22e">i</span>] = <span style="color:#a6e22e">p</span>[<span style="color:#a6e22e">i</span>].<span style="color:#a6e22e">Plus</span>(<span style="color:#a6e22e">v</span>.<span style="color:#a6e22e">String</span>())
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">r</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>与常规的入参、出参类型声明一样的规则。</p>
<h3 id="定义运算符约束">定义运算符约束</h3>
<p>完成了函数约束的定义后，剩下一个要啃的大骨头就是 “运算符” 的约束了。</p>
<h4 id="问题点-1">问题点</h4>
<p>我们看看 Go 官方的例子：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Smallest</span>[<span style="color:#a6e22e">T</span> <span style="color:#a6e22e">any</span>](<span style="color:#a6e22e">s</span> []<span style="color:#a6e22e">T</span>) <span style="color:#a6e22e">T</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">r</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">s</span>[<span style="color:#ae81ff">0</span>] <span style="color:#75715e">// panic if slice is empty
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">v</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">s</span>[<span style="color:#ae81ff">1</span>:] {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">v</span> &lt; <span style="color:#a6e22e">r</span> { <span style="color:#75715e">// INVALID
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>			<span style="color:#a6e22e">r</span> = <span style="color:#a6e22e">v</span>
</span></span><span style="display:flex;"><span>		}
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">r</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>经过上面的函数例子，我们很快能意识到这个程序根本无法运行成功。</p>
<p>其入参是 <code>any</code> 类型，程序内部是按 slice 类型来获取值，且在内部又进行运算符比较，那如果真是 slice，内部就可能每个值类型都不一样。</p>
<p>如果一个是 slice，一个是 int 类型，又如何进行运算符的值对比？</p>
<h4 id="近似元素">近似元素</h4>
<p>可能有的同学想到了重载运算符，但&hellip;想太多了，Go 语言没有支持的计划。为此做了一个新的设计，那就是允许限制类型参数的类型范围。</p>
<p>语法如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a6e22e">InterfaceType</span>  = <span style="color:#e6db74">&#34;interface&#34;</span> <span style="color:#e6db74">&#34;{&#34;</span> {(<span style="color:#a6e22e">MethodSpec</span> | <span style="color:#a6e22e">InterfaceTypeName</span> | <span style="color:#a6e22e">ConstraintElem</span>) <span style="color:#e6db74">&#34;;&#34;</span> } <span style="color:#e6db74">&#34;}&#34;</span> .
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">ConstraintElem</span> = <span style="color:#a6e22e">ConstraintTerm</span> { <span style="color:#e6db74">&#34;|&#34;</span> <span style="color:#a6e22e">ConstraintTerm</span> } .
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">ConstraintTerm</span> = [<span style="color:#e6db74">&#34;~&#34;</span>] <span style="color:#a6e22e">Type</span> .
</span></span></code></pre></div><p>例子如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">AnyInt</span> <span style="color:#66d9ef">interface</span>{ ~<span style="color:#66d9ef">int</span> }
</span></span></code></pre></div><p>上述声明的类型集是 <code>~int</code>，也就是所有类型为 int 的类型（如：int、int8、int16、int32、int64）都能够满足这个类型约束的条件。</p>
<p>包括底层类型是 int8 类型的，例如：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">AnyInt8</span> <span style="color:#66d9ef">int8</span>
</span></span></code></pre></div><p>也就是在该匹配范围内的。</p>
<h4 id="联合元素">联合元素</h4>
<p>如果希望进一步缩小限定类型，可以结合分隔符来使用，用法为：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">AnyInt</span> <span style="color:#66d9ef">interface</span>{
</span></span><span style="display:flex;"><span> ~<span style="color:#66d9ef">int8</span> | ~<span style="color:#66d9ef">int64</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>就可以将类型集限定在 int8 和 int64 之中。</p>
<h4 id="实现运算符约束">实现运算符约束</h4>
<p>基于新的语法，结合新的概念联合和近似元素，可以把程序改造一下，实现在泛型中的运算符的匹配。</p>
<p>类型约束的声明，如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Ordered</span> <span style="color:#66d9ef">interface</span> {
</span></span><span style="display:flex;"><span>	~<span style="color:#66d9ef">int</span> | ~<span style="color:#66d9ef">int8</span> | ~<span style="color:#66d9ef">int16</span> | ~<span style="color:#66d9ef">int32</span> | ~<span style="color:#66d9ef">int64</span> |
</span></span><span style="display:flex;"><span>		~<span style="color:#66d9ef">uint</span> | ~<span style="color:#66d9ef">uint8</span> | ~<span style="color:#66d9ef">uint16</span> | ~<span style="color:#66d9ef">uint32</span> | ~<span style="color:#66d9ef">uint64</span> | ~<span style="color:#66d9ef">uintptr</span> |
</span></span><span style="display:flex;"><span>		~<span style="color:#66d9ef">float32</span> | ~<span style="color:#66d9ef">float64</span> |
</span></span><span style="display:flex;"><span>		~<span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>应用的程序如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Smallest</span>[<span style="color:#a6e22e">T</span> <span style="color:#a6e22e">Ordered</span>](<span style="color:#a6e22e">s</span> []<span style="color:#a6e22e">T</span>) <span style="color:#a6e22e">T</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">r</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">s</span>[<span style="color:#ae81ff">0</span>] <span style="color:#75715e">// panics if slice is empty
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">v</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">s</span>[<span style="color:#ae81ff">1</span>:] {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">v</span> &lt; <span style="color:#a6e22e">r</span> {
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">r</span> = <span style="color:#a6e22e">v</span>
</span></span><span style="display:flex;"><span>		}
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">r</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>确保了值均为基础数据类型后，程序就可以正常运行了。</p>
<h2 id="类型推导">类型推导</h2>
<p>程序员写代码，一定程度的偷懒是必然的。</p>
<p>在一定的场景下，可以通过类型推导来避免明确地写出一些或所有的类型参数，编译器会进行自动识别。</p>
<p>建议复杂函数和参数能明确是最好的，否则读代码的同学会比较麻烦，可读性和可维护性的保证也是工作中重要的一点。</p>
<h3 id="参数推导">参数推导</h3>
<p>函数例子。如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Map</span>[<span style="color:#a6e22e">F</span>, <span style="color:#a6e22e">T</span> <span style="color:#a6e22e">any</span>](<span style="color:#a6e22e">s</span> []<span style="color:#a6e22e">F</span>, <span style="color:#a6e22e">f</span> <span style="color:#66d9ef">func</span>(<span style="color:#a6e22e">F</span>) <span style="color:#a6e22e">T</span>) []<span style="color:#a6e22e">T</span> { <span style="color:#f92672">...</span> }
</span></span></code></pre></div><p>公共代码片段。如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">s</span> []<span style="color:#66d9ef">int</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">f</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">func</span>(<span style="color:#a6e22e">i</span> <span style="color:#66d9ef">int</span>) <span style="color:#66d9ef">int64</span> { <span style="color:#66d9ef">return</span> int64(<span style="color:#a6e22e">i</span>) }
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">r</span> []<span style="color:#66d9ef">int64</span>
</span></span></code></pre></div><p>明确指定两个类型参数。如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a6e22e">r</span> = <span style="color:#a6e22e">Map</span>[<span style="color:#66d9ef">int</span>, <span style="color:#66d9ef">int64</span>](<span style="color:#a6e22e">s</span>, <span style="color:#a6e22e">f</span>)
</span></span></code></pre></div><p>只指定第一个类型参数，变量 f 被推断出来。如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a6e22e">r</span> = <span style="color:#a6e22e">Map</span>[<span style="color:#66d9ef">int</span>](<span style="color:#a6e22e">s</span>, <span style="color:#a6e22e">f</span>)
</span></span></code></pre></div><p>不指定任何类型参数，让两者都被推断出来。如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#a6e22e">r</span> = <span style="color:#a6e22e">Map</span>(<span style="color:#a6e22e">s</span>, <span style="color:#a6e22e">f</span>)
</span></span></code></pre></div><h3 id="约束推导">约束推导</h3>
<p>神奇的在于，类型推导不仅限与此，连约束都可以推导。</p>
<p>函数例子，如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Double</span>[<span style="color:#a6e22e">E</span> <span style="color:#a6e22e">constraints</span>.<span style="color:#a6e22e">Number</span>](<span style="color:#a6e22e">s</span> []<span style="color:#a6e22e">E</span>) []<span style="color:#a6e22e">E</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">r</span> <span style="color:#f92672">:=</span> make([]<span style="color:#a6e22e">E</span>, len(<span style="color:#a6e22e">s</span>))
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">i</span>, <span style="color:#a6e22e">v</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">s</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">r</span>[<span style="color:#a6e22e">i</span>] = <span style="color:#a6e22e">v</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">v</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">r</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>基于此的推导案例，如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">MySlice</span> []<span style="color:#66d9ef">int</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">V1</span> = <span style="color:#a6e22e">Double</span>(<span style="color:#a6e22e">MySlice</span>{<span style="color:#ae81ff">1</span>})
</span></span></code></pre></div><p>MySlice 是一个 int 的切片类型别名。变量 V1 的类型编译器推导后 []int 类型，并不是 MySlice。</p>
<p>原因在于编译器在比较两者的类型时，会将 MySlice 类型识别为 []int，也就是 int 类型。</p>
<p>要实现 “正确” 的推导，需要如下定义：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">SC</span>[<span style="color:#a6e22e">E</span> <span style="color:#a6e22e">any</span>] <span style="color:#66d9ef">interface</span> {
</span></span><span style="display:flex;"><span>	[]<span style="color:#a6e22e">E</span> 
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">DoubleDefined</span>[<span style="color:#a6e22e">S</span> <span style="color:#a6e22e">SC</span>[<span style="color:#a6e22e">E</span>], <span style="color:#a6e22e">E</span> <span style="color:#a6e22e">constraints</span>.<span style="color:#a6e22e">Number</span>](<span style="color:#a6e22e">s</span> <span style="color:#a6e22e">S</span>) <span style="color:#a6e22e">S</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">r</span> <span style="color:#f92672">:=</span> make(<span style="color:#a6e22e">S</span>, len(<span style="color:#a6e22e">s</span>))
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">i</span>, <span style="color:#a6e22e">v</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">s</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">r</span>[<span style="color:#a6e22e">i</span>] = <span style="color:#a6e22e">v</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">v</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">r</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>基于此的推导案例。如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">V2</span> = <span style="color:#a6e22e">DoubleDefined</span>[<span style="color:#a6e22e">MySlice</span>, <span style="color:#66d9ef">int</span>](<span style="color:#a6e22e">MySlice</span>{<span style="color:#ae81ff">1</span>})
</span></span></code></pre></div><p>只要定义显式类型参数，就可以获得正确的类型，变量 V2 的类型会是 MySlice。</p>
<p>那如果不声明约束呢？如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">V3</span> = <span style="color:#a6e22e">DoubleDefined</span>(<span style="color:#a6e22e">MySlice</span>{<span style="color:#ae81ff">1</span>})
</span></span></code></pre></div><p>编译器通过函数参数进行推导，也可以明确变量 V3 类型是 MySlice。</p>
<h2 id="总结">总结</h2>
<p>今天我们在文章中给大家介绍了泛型的三个重要概念，分别是：</p>
<ul>
<li>类型参数：泛型的抽象数据类型。</li>
<li>类型约束：确保调用方能够满足接受方的程序诉求。</li>
<li>类型推导：避免明确地写出一些或所有的类型参数。</li>
</ul>
<p>在内容中也涉及到了联合元素、近似元素、函数约束、运算符约束等新概念。本质上都是基于三个大概念延伸出来的新解决方法，一环扣一环。</p>
<p>你学会 Go 泛型了吗，设计的如何，欢迎一起和煎鱼讨论：）</p>
<h2 id="参考">参考</h2>
<ul>
<li><a href="https://go.googlesource.com/proposal/+/refs/heads/master/design/43651-type-parameters.md">Type Parameters Proposal</a></li>
<li><a href="https://docs.google.com/document/d/1vrAy9gMpMoS3uaVphB32uVXX4pi-HnNjkMEgyAHX4N4/">Summary of Go Generics Discussions</a></li>
</ul>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/nil-func/">Go 读者提问：值为 nil 也能调用函数，太神奇了吧？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/throw/">Go 有哪些无法恢复的致命场景？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/import-generics/">长达 12 年，Go 才引入泛型，是政治，还是技术问题？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/again-mutex/">Go 为什么不支持可重入锁？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/switch-type/">Go 泛型玩出花，详解新提案 switch type！</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/nil-func/"
                                                    rel="prev">Go 读者提问：值为 nil 也能调用函数，太神奇了吧？</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/map-con/">Go 为什么不在语言层面支持 map 并发？</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>